package com.lakeworks.decision.handler;

import com.lakeworks.common.domain.channel.ticket.TicketChannel;
import com.lakeworks.common.domain.ticket.TktDecision;
import com.lakeworks.common.domain.ticket.TktTicket;
import com.lakeworks.common.domain.ticket.TktTicketFile;
import com.lakeworks.common.exception.response.ResponseException;
import com.lakeworks.decision.PushTicketDecision;
import com.lakeworks.decision.base.BaseDecisionHandler;
import com.lakeworks.decision.base.DecisionHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.stream.Collectors;

@Component
public class PushTicketDecisionHandler extends BaseDecisionHandler implements DecisionHandler<PushTicketDecision> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TktDecision apply(PushTicketDecision decision) {
        TktTicket ticket = decision.getTktTicket();
        System.out.println("执行推送工单决策");
        TicketChannel build = TicketChannel.builder()
                .ticketId(ticket.getId())
                .orderNo(ticket.getOrderNo())
                .type(ticket.getType())
                .title(ticket.getTitle())
                .priority(ticket.getPriority())
                .label(ticket.getLabel())
                .operator(ticket.getCreateBy())
                .barcode(ticket.getBarcode())
                .comment(ticket.getRemark())
                .build();
        if (!CollectionUtils.isEmpty(ticket.
                getTktTicketFiles())) {
            build.setVouchers(ticket.getTktTicketFiles().stream().map(TktTicketFile::getFileUrl).collect(Collectors.toList()));
        }
        //向平台推送洗涤售后工单
        getLog().info("推送工厂创建工单信息----param:[{}]",build);
        Long channelId = getChannelId(ticket.getOrderNo());
        Map map = getMerchantAsync().pushTicket(build,channelId);
        String code = String.valueOf(map.get("code"));
        if(!code.equals("200")){
            throw new ResponseException("推送工单信息失败");
        }
        //触发工单暂停事件，将该订单下的所有衣物给暂停
        //getApplicationContext().publishEvent(new TicketHoldingEvent(this, ticket.getOrderNo()));
        ticket.setChannelTicketId(Long.valueOf(String.valueOf(map.get("body"))));
        ticket.setChannelId(channelId);
        updateTicketState(ticket);
        return getTktDecision(ticket, decision);
    }

}
